package JDBC_1.exer;

import JDBC_1.util.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Scanner;

/**
 * @author ：Yan Guang
 * @date ：Created in 2020/5/13 15:03
 * @description： 添加操作升级版
 */
public class Exer2test {
    //向表中添加数据
    /*
    *   Type:
        IDCard:
        ExamCard :
        StudentName:
        Location:
        Grade:

    * */
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("四级/六级： ");
        int type = scanner.nextInt();
        System.out.print("输出身份证号码: ");
        String IDCard = scanner.next();
        System.out.print("准考证号： ");
        String examCard = scanner.next();
        System.out.print("学生姓名: ");
        String studentName = scanner.next();
        System.out.print("所在城市: ");
        String location = scanner.next();
        System.out.print("考试成绩： ");
        int grade = scanner.nextInt();

        String sql="insert into examstudent(type,IDCard,examCard,studentName,location,grade)values(?,?,?,?,?,?) ";
        int insertcount = update(sql, type, IDCard, examCard, studentName, location, grade);
        if (insertcount>0){
            System.out.println("添加成功！");
        }else {
            System.out.println("添加失败！");
        }
    }

    public static int update(String sql, Object... args) {
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            //1.获取连接
            connection = JDBCUtils.getConnection();
            //2.预写sql
            ps = connection.prepareStatement(sql);
            //3.填充占位符
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);//小心参数声明错误
            }
            //4.执行语句
            /*
            如果是一个查询操作有返回结果就返回true，如果是层删改操作就返回false
            * */
            ps.execute();
            return ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //5.关闭
            JDBCUtils.closeResourece(connection, ps);
        }
        return 0;
    }
}
